<template>
  <div class="person-wrapper">
    <div>
      <div class="person-info">
        <img class="person-img" @click="changeHeadImg" :src="personInfo.headThumbUrl" />
        <div class="person-text">
          <div class="person-name" @click="editInfo('nickname')">
            {{typeof personInfo.nickname === 'undefined' || personInfo.nickname === null ? placeholder[2] : personInfo.nickname}}
          </div>
          <div class="person-intro" @click="editInfo('intro')">
            {{typeof personInfo.intro === 'undefined' || personInfo.intro === null ? placeholder[3] : personInfo.intro}}
          </div>
        </div>
        <div id="id4" style="clear:both"></div>
      </div>

      <div class="group">
        <div @click="showEnterList(1)">
          <mt-cell title="我的报名" is-link>
            <mt-badge size="small" type="success">{{ count.applyCount }}</mt-badge>
            <span>点击查看</span>
          </mt-cell>
        </div>
        <div @click="showEnterList(2)">
          <mt-cell title="收藏列表" is-link>
            <mt-badge size="small" type="success">{{ count.scCount }}</mt-badge>
            <span>点击查看</span>
          </mt-cell>
        </div>
        <div @click="showMessage">
          <mt-cell title="我的消息" is-link>
            <mt-badge size="small">{{ count.msgCount }}</mt-badge>
            <span>查看消息</span>
          </mt-cell>
        </div>
        <div @click="showEnterList(3)">
          <mt-cell title="浏览历史" is-link>
            <span>最近浏览{{ count.count }}条记录</span>
          </mt-cell>
        </div>
      </div>

      <!-- 资料列表 -->
      <div class="group">
        <div @click="editInfo('realname')">
          <mt-cell title="真实姓名" :value="typeof personInfo.realname === 'undefined' || personInfo.realname === null ? placeholder[0] : personInfo.realname" is-link></mt-cell>
          <font class="require">*</font>
        </div>
        <div @click="editInfo('phone')">
          <mt-cell title="手机号" :value="typeof personInfo.phone === 'undefined' || personInfo.phone === null ? placeholder[0] : personInfo.phone" is-link></mt-cell>
          <font class="require">*</font>
        </div>
        <div @click="showsexStrPick">
          <mt-cell title="性别" :value="typeof personInfo.sexStr === 'undefined' || personInfo.sexStr === null ? placeholder[1] : personInfo.sexStr" is-link></mt-cell>
          <font class="require">*</font>
        </div>
        <div @click="showDatePick">
          <mt-cell title="生日" :value="typeof personInfo.birthday === 'undefined' || personInfo.birthday === null ? placeholder[1] : personInfo.birthday" is-link></mt-cell>
          <font class="require">*</font>
        </div>
        <div @click="editInfo('schoolName')">
          <mt-cell title="学校" :value="typeof personInfo.schoolName === 'undefined' || personInfo.schoolName === null ? placeholder[0] : personInfo.schoolName" is-link></mt-cell>
          <font class="require">*</font>
        </div>
        <div @click="editInfo('academyName')">
          <mt-cell title="学院" :value="typeof personInfo.academyName === 'undefined' || personInfo.academyName === null ? placeholder[0] : personInfo.academyName" is-link></mt-cell>
          <font class="require">*</font>
        </div>
        <div @click="editInfo('major')">
          <mt-cell title="专业" :value="typeof personInfo.major === 'undefined' || personInfo.major === null ? placeholder[0] :  personInfo.major" is-link></mt-cell>
          <font class="require">*</font>
        </div>
        <div @click="showGradePick">
          <mt-cell title="年级" :value="typeof personInfo.grade === 'undefined' || personInfo.grade === null ? placeholder[1] :  personInfo.grade" is-link></mt-cell>
          <font class="require">*</font>
        </div>
        <div @click="editInfo('qq')">
          <mt-cell title="QQ" :value="typeof personInfo.qq === 'undefined' || personInfo.qq === null ? placeholder[0] : personInfo.qq" is-link></mt-cell>
          <font class="require">*</font>
        </div>
      </div>

      <div style="text-align: center; margin-bottom: 85px; margin-top: 25px;">
        <el-button @click="logout" type="danger" round size="large" style="width: 75%">退出登录</el-button>
      </div>
    </div>

    <mt-popup v-model="popupVisible" class="" popup-transition="popup-fade" :closeOnClickModal="false" class="no-person">
        <el-button type="warning" round plain size="large" @click="toLogin">点我登录</el-button>
    </mt-popup>

    <mt-datetime-picker ref="dateTimePicker" type="date" :startDate="this.dataTimeConfig.startDate" :endDate="this.dataTimeConfig.endDate" v-model="datetimePickerVisible" @confirm="datetimePickerConfirm">
    </mt-datetime-picker>
    <mt-actionsheet :actions="sexStr" v-model="sexStrSheetViesible">
    </mt-actionsheet>
    <mt-actionsheet :actions="grade" v-model="gradeSheetViesible">
    </mt-actionsheet>
  </div>
</template>

<script>
import { MessageBox } from 'mint-ui'
import { Toast } from 'mint-ui'
import { mapGetters } from 'vuex'

import axios from '@/api/axiosApi'
import wechatApi from '@/api/wechatApi'
import { formatDate } from 'assets/js/utils'
import defaultAvatar from '@/assets/images/default_avatar.png'

export default {
  data () {
    return {
      defaultAvatar,
      placeholder: [
        '请输入',
        '请选择',
        '请输入昵称',
        '暂无简介',
        '请输入学校全称'
      ],
      popupVisible: false,
      datetimePickerVisible: new Date(),
      dataTimeConfig: {
        startDate: new Date('1970-01-01'),
        endDate: new Date()
      },
      value: new Date(),
      sexStr: [{
        id: 1,
        name: '男',
        method: this.sexStrConfirm
      },
      {
        id: 2,
        name: '女',
        method: this.sexStrConfirm
      }
      ],
      sexStrSheetViesible: false,
      gradeSheetViesible: false,
      grade: [
        {
          name: new Date().getFullYear() - 4 + '级',
          method: this.gradeConfirm
        },
        {
          name: new Date().getFullYear() - 3 + '级',
          method: this.gradeConfirm
        }, {
          name: new Date().getFullYear() - 2 + '级',
          method: this.gradeConfirm
        }, {
          name: new Date().getFullYear() - 1 + '级',
          method: this.gradeConfirm
        }, {
          name: new Date().getFullYear() + '级',
          method: this.gradeConfirm
        }
      ]
    }
  },
  created () {
    const openId = localStorage.getItem('openId')
    if (openId !== null) {
      this._getPersonInfo()
      this.popupVisible = false
    } else {
      this.popupVisible = true
    }
  },
  watch: {
    '$route' (to, from) {
      if (to.name === 'person') {
        const openId = localStorage.getItem('openId')
        if (openId !== null) {
          this._getPersonInfo()
          this.popupVisible = false
        } else {
          this.popupVisible = true
        }
      }
    }
  },
  methods: {
    _getPersonInfo () {
      const _self = this
      const openId = localStorage.getItem('openId')
      if (openId) {
        axios.post('/student/findByOpenId', {openId: openId}, (data) => {
          if (typeof data.headThumbUrl === 'undefined' || data.headThumbUrl === null) {
            data.headThumbUrl = defaultAvatar
          }
          if (data.salesCode && data.salesCode !== null) {
            _self.$route.query.salesCode = data.salesCode
          }
          _self.$store.commit('changePersonInfo', data)
        })
      }
    },
    toLogin () {
      let ua = window.navigator.userAgent.toLowerCase()
      if (ua.match(/micromessenger/i) == 'micromessenger') {
        // 如果是微信浏览器，直接微信登录
        wechatApi.wechatLogin()
      } else {
        // 否则跳到登录页面(短信、微信、QQ)
        this.$router.push({
          path: '/wechat/login',
          query: this.$route.query
        })
      }
      /*
      else if (ua.match(/QQ/i) == 'qq') {
        // 在QQ空间打开
      }
      */
    },
    logout () {
      this.popupVisible = true
      document.body.scrollTop = 0
      localStorage.removeItem('openId')
      window.location.reload()
    },
    showMessage () {
      this.$router.push({
        path: '/wechat/message/0',
        query: this.$route.query
      })
    },
    showDatePick () {
      this.$refs.dateTimePicker.open()
    },
    showsexStrPick () {
      this.sexStrSheetViesible = true
    },
    showGradePick () {
      this.gradeSheetViesible = true
    },
    changeHeadImg () {
      // Toast({
      //   message: '暂不支持头像更换',
      //   position: 'center',
      //   duration: 4000
      // });
    },
    showEnterList (type) {
      this.$router.push({
        path: `/wechat/enterList/${type}`,
        query: this.$route.query
      })
    },
    editInfo (type) {
      let message = ''
      let inputValue = ''
      let inputPlaceholder = ''
      switch (type) {
        case 'realname':
          message = '真实姓名'
          inputValue = this.personInfo.realname
          inputPlaceholder = '请输入真实姓名'
          break
        case 'schoolName':
          message = '学校名称'
          inputPlaceholder = '请输入学校全称'
          inputValue = this.personInfo.schoolName
          break
        case 'academyName':
          message = '学院名称'
          inputPlaceholder = '请输入学院名称'
          inputValue = this.personInfo.academyName
          break
        case 'major':
          message = '专业名称'
          inputPlaceholder = '请输入专业名称'
          inputValue = this.personInfo.major
          break
        case 'phone':
          message = '手机号'
          inputPlaceholder = '请输入手机号'
          inputValue = this.personInfo.phone
          break
        case 'qq':
          message = 'QQ号'
          inputPlaceholder = '请输入QQ号'
          inputValue = this.personInfo.qq
          break
        case 'nickname':
          message = '昵称'
          inputPlaceholder = '请输入昵称'
          inputValue = this.personInfo.nickname
          break
        case 'intro':
          message = '简介'
          inputPlaceholder = '请输入简介'
          inputValue = this.personInfo.intro
          break
        default:
      }
      MessageBox.prompt(' ', message, {
        showCancelButton: true,
        showInput: true,
        inputValue,
        inputPlaceholder,
      }).then(({
        value,
        action
      }) => {
        if (action === 'confirm') {
          switch (type) {
            case 'realname':
              this.personInfo.realname = value
              this.updateUserInfo('realname', value)
              break
            case 'schoolName':
              this.personInfo.schoolName = value
              this.updateUserInfo('schoolName', value)
              break
            case 'academyName':
              this.personInfo.academyName = value
              this.updateUserInfo('academyName', value)
              break
            case 'major':
              this.personInfo.major = value
              this.updateUserInfo('major', value)
              break
            case 'phone':
              if (!(/^1[34578]\d{9}$/.test(value))) {
                Toast('请输入正确的手机号码')
                return
              }
              this.personInfo.phone = value
              this.updateUserInfo('phone', value)
              break
            case 'qq':
              this.updateUserInfo('qq', value)
              this.personInfo.qq = value
              break
            case 'nickname':
              this.personInfo.nickname = value
              this.updateUserInfo('nickname', value)
              break
            case 'intro':
              this.personInfo.intro = value
              this.updateUserInfo('intro', value)
              break
            default:
          }
          this.$store.commit('changePersonInfo', this.personInfo)
        }
      })
      // MessageBox.prompt(message, '').then(({
      //   value,
      //   action
      // }) => {
      //
      // });
    },
    // 更新生日
    datetimePickerConfirm (value) {
      this.personInfo.birthday = formatDate(value, 'yyyy-MM-dd')
      this.$store.commit('changePersonInfo', this.personInfo)
      this.updateUserInfo('birthday', this.personInfo.birthday)
    },
    sexStrConfirm (sexStr) {
      this.personInfo.sexStr = sexStr.name
      this.$store.commit('changePersonInfo', this.personInfo)
      this.updateUserInfo('sex', sexStr.name)
    },
    gradeConfirm (grade) {
      this.personInfo.grade = grade.name
      this.$store.commit('changePersonInfo', this.personInfo)
      this.updateUserInfo('grade', this.personInfo.grade)
    },
    updateUserInfo (key, value) {
      if (key === 'sex') {
        value = value === '男' ? 1 : 2
      }
      let openId = localStorage.getItem('openId')
      if (!openId) openId = this.personInfo.openId
      let params = {}
      params['openId'] = openId
      params[key] = value
      axios.post('/student/addOrUpdateStudent', params, (data) => {
        Toast('修改成功')
      })
    }
  },
  computed: {
    ...mapGetters([
      'personInfo',
      'count'
    ])
  },
  name: 'person'
}
</script>

<style>
.group .mint-cell-wrapper {
  font-size: 14px;
  background-image: none;
  border: none;
}
.person-wrapper .v-modal {
    z-index: 1;
    bottom: 58px;
    height: auto;
}
</style>

<style lang='stylus' scoped>
@import '~assets/stylus/variable.styl';

.person-wrapper {
  position: relative;
  overflow-y: hidden;

  .no-person {
    background: none;
    width: 100%;
    text-align: center;
    margin-top: 0px;
  }

  .require {
    color: red;
    position: absolute;
    top: 15px;
    left: 2px;
  }
}

.person-info {
  background-color: #6ed6ab;
  color: #ffffff;
  padding: 3% 5% 3% 5%;

  .person-img {
    float: left;
    width: 88px;
    height: 88px;
  }

  .person-text {
    float: left;
    width: 60%;
    margin-top: 5.5%;
    margin-left: 7%;
    text-align: left;

    .person-name {
      font-size: 18px;
      font-weight: bold;
    }

    .person-intro {
      font-size: 13px;
      color: #efefef;
      margin-top: 8%;
    }
  }
}

.group {
  margin-top: 35px;

  .title {
    font-size: 16px;
    padding: 8px 12px;
    color: $color-text-dark;
  }

  div {
    position: relative;
    border-bottom: 1px solid $color-border-3;

    &:last-child {
      border-bottom: none;
    }

    .mint-cell {
      min-height: 42px;
      background: #fff;

      .mint-badge {
        position: absolute;
        top: 7px;
        left: 72px;
      }

      span {
        font-size: 13px;
      }
    }
  }
}
</style>
